package com.studentstreet;

import java.io.IOException;

import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.studentstreet.component.LwtAlertDialog;
import com.studentstreet.component.StarLayout;
import com.studentstreet.entities.CommentCount;
import com.studentstreet.entities.GoodsEntity;
import com.studentstreet.tools.HtmlTools;
import com.studentstreet.tools.HttpHelper;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.SyncImageLoader;
import com.studentstreet.tools.Util;
import com.studentstreet.tools.dbhelper.GoodsDBHelper;
import com.studentstreet.tools.dbhelper.OrderDBHelper;

/**
 * @author likebamboo
 * 
 */
public class GoodsDetailActivity extends TabActivity implements
		OnGestureListener {
	// Title标题
	private TextView titleText;
	// Login Button登录按钮
	private Button login_bt;
	// 头部左边的按钮
	private ImageButton backImgBt = null;
	// 商品图案
	private ImageView goodsImage = null;
	// 所属商家
	private TextView goodsSellerText = null;
	// 价格
	private TextView goodsPriceText = null;
	// 类别
	private TextView goodsClassText = null;
	// 销售量
	private TextView goodsSaleCountText = null;
	// 评分
	private RatingBar goodsRank = null;
	// 添加至购物车
	private Button addToCartButton = null;
	// 添加至购物车
	private Button addToFavoriteButton = null;

	// 评论和商品详情TabHost
	private TabHost mTabHost;
	// TabWidget
	private TabWidget tabWidget;
	// 评分详情布局（自己写的）
	private StarLayout commentStar;
	// 商品详情内容
	private TextView goodsDetailText;

	// 用于保存数据的Goods实体
	private GoodsEntity goods = null;
	// 资源文件
	private Resources res = null;

	// 用户名
	private String userName = "";
	// 标记该商品是否加入收藏夹
	private boolean addToFavor = false;

	// OEM++ 侧边栏菜单的手势效果 @ 2013-1-15
	private GestureDetector gestureDetector;

	// OEM--

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.goods_details);
		// 将当前Activity压入堆栈中
		MyApp.getInstance().addActivity(this);
		res = getResources();

		// OEM++ liwt@2013-1-15
		gestureDetector = new GestureDetector(this);
		// OEM--

		// 初始化布局
		initUI();

	}

	// 初始化布局
	private void initUI() {
		// 获得上个Activity所传过来的参数
		Intent intent = getIntent();
		Bundle bundle = intent.getBundleExtra("goods_detail");
		// 获得传递过来的Goods对象
		goods = bundle.getParcelable("goods");
		// 初始化头部
		// 返回按钮
		backImgBt = (ImageButton) findViewById(R.id.header_imgBt);
		// 头部中间的标题
		titleText = (TextView) findViewById(R.id.title);
		// 登录按钮
		login_bt = (Button) findViewById(R.id.login_bt);

		// 初始化商品基本信息
		goodsImage = (ImageView) findViewById(R.id.goods_img);
		goodsSellerText = (TextView) findViewById(R.id.detail_seller);
		goodsPriceText = (TextView) findViewById(R.id.detail_price);
		goodsClassText = (TextView) findViewById(R.id.detail_class);
		goodsSaleCountText = (TextView) findViewById(R.id.detail_saleCount);
		goodsRank = (RatingBar) findViewById(R.id.detail_rank_RatingBar);

		addToCartButton = (Button) findViewById(R.id.add_to_cart);
		addToFavoriteButton = (Button) findViewById(R.id.add_to_want);

		mTabHost = getTabHost();

		login_bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(GoodsDetailActivity.this,
						LoginDialog.class);
				startActivity(intent);
			}
		});
		// 返回按钮
		backImgBt.setImageResource(R.drawable.back);
		backImgBt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 如果将当前商品添加到了收藏夹，则需通知商品列表界面更新界面
				if (addToFavor) {
					setResult(RESULT_OK);
				}
				finish();
			}
		});
		// 头部中间的标题（设置为商品名）
		titleText.setText(goods.getName());

		// 设置商品的图片
		Drawable d = null;
		try {
			d = SyncImageLoader.loadImageFromUrl(goods.getImageUrl());
		} catch (IOException e) {
			Toast.makeText(this, res.getString(R.string.load_img_failed),
					Toast.LENGTH_SHORT).show();
		}
		goodsImage.setImageDrawable(d);

		// 设置商品所属商家名
		goodsSellerText.setText(HtmlTools.getSeller(
				this.getApplicationContext(), goods.getSellerName()));
		// 设置商品价格
		goodsPriceText.setText(HtmlTools.getPrice(this.getApplicationContext(),
				goods.getPrice() + ""));
		// 设置商品类别
		goodsClassText.setText(HtmlTools.getClass(this.getApplicationContext(),
				goods.getClassName()));
		// 设置商品销售量
		goodsSaleCountText.setText(HtmlTools.getCount(
				this.getApplicationContext(), goods.getSaleCount() + ""));
		// 设置商品评级
		goodsRank.setRating((float) goods.getRank());

		// 添加至购物车按钮
		addToCartButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String positive = res.getString(R.string.sure);
				String negative = res.getString(R.string.cancel);
				String title = "";
				String msg = "";
				PreferenceTools prefTools = new PreferenceTools(
						GoodsDetailActivity.this);
				// 判断是否已经登录
				if (!prefTools.isLogin()) {
					// 如果未登录显示登录对话框
					title = res.getString(R.string.not_login);
					msg = res.getString(R.string.login_or_not);
					Intent loginIntent = new Intent(GoodsDetailActivity.this,
							LoginDialog.class);
					showDialog(title, msg, positive, negative, loginIntent);
				} else {
					// 已登录，将数据添加到数据库
					Intent goCartIntent = new Intent(GoodsDetailActivity.this,
							CartActivity.class);
					title = res.getString(R.string.tips);
					long result = insertInDB();
					if (result <= 0) {
						// 数据已有该记录，显示对话框
						if (result == 0) {
							// 显示是否要去购物车查询对话框
							msg = res.getString(R.string.already_in_cart);
							showDialog(title, msg, positive, negative,
									goCartIntent);
							return;
						}
						// 插入失败，显示提示信息
						Toast.makeText(GoodsDetailActivity.this,
								res.getString(R.string.save_to_db_failed),
								Toast.LENGTH_SHORT).show();
						return;
					}
					// OEM++商品已添加到购物车，修改购物车图标
					if (Util.OEM) {
						setCartIcon();
					}
					// 显示是否要去购物车查询对话框
					msg = res.getString(R.string.go_to_cart_or_not);
					showDialog(title, msg, positive, negative, goCartIntent);
				}
			}

		});

		// 添加至收藏夹按钮
		addToFavoriteButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				PreferenceTools prefTools = new PreferenceTools(
						getApplicationContext());
				if (!prefTools.isLogin()) {
					// 如果用户未登录,显示提示，不操作数据库
					Toast.makeText(getApplicationContext(),
							res.getString(R.string.have_no_login),
							Toast.LENGTH_SHORT).show();
					return;
				}
				GoodsDBHelper dbHelper = new GoodsDBHelper(
						GoodsDetailActivity.this);
				// 如果该商品收藏夹中没有,则保存
				if (dbHelper.isFavorite(goods.getId(), userName) == GoodsDBHelper.MOVE_FAVORITE) {
					// 保存数据成功
					if (dbHelper.saveToStore(goods, userName) > 0) {
						Toast.makeText(getApplicationContext(),
								res.getString(R.string.add_to_favorite),
								Toast.LENGTH_SHORT).show();
						// 标记商品已添加到收藏夹
						addToFavor = true;
					} else {
						// 保存数据失败
						Toast.makeText(getApplicationContext(),
								res.getString(R.string.failed_to_favorite),
								Toast.LENGTH_SHORT).show();
					}
				} else {
					// 如果该商品收藏夹中已有,显示提示
					Toast.makeText(getApplicationContext(),
							res.getString(R.string.already_favorite),
							Toast.LENGTH_LONG).show();
				}
			}
		});

		// OEM++ liwt 2013-05-09 如果商品下架了。
		if (goods.getState() != 1) {
			addToCartButton.setText("商品已下架");
			addToCartButton.setEnabled(false);
			addToFavoriteButton.setEnabled(false);
		}

		// 设置商品评论和商品详情的TabHost
		TabSpec commentTab = mTabHost.newTabSpec("commentCount")
				.setIndicator(getResources().getString(R.string.comment))
				.setContent(R.id.star_layout);
		TabSpec detailInfoTab = mTabHost.newTabSpec("detailInfo")
				.setIndicator(getResources().getString(R.string.detail_info))
				.setContent(R.id.goods_detail_info);
		mTabHost.addTab(commentTab);
		mTabHost.addTab(detailInfoTab);

		tabWidget = mTabHost.getTabWidget();
		// 设置TabWidget的布局
		for (int i = 0; i < tabWidget.getChildCount(); i++) {
			View v = tabWidget.getChildTabViewAt(i);
			// 设置Tab的高度与背景
			v.getLayoutParams().height = (int) (getWindowManager()
					.getDefaultDisplay().getHeight() * 0.1);
			// Tab上的文字的属性
			TextView tv = (TextView) v.findViewById(android.R.id.title);
			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tv
					.getLayoutParams();
			// 取消文字底边对齐
			params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
			// 设置文字居中对齐
			params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

		}
		// 商品评论StarLayout(自己写的)
		commentStar = (StarLayout) findViewById(R.id.star_layout);
		// 商品详细信息
		goodsDetailText = (TextView) findViewById(R.id.goods_detail_info);
		// 设置商品详细信息
		goodsDetailText.setText(goods.getDescrition());
		// 当点击商品评论StarLayout时，跳转到商品评论列表中
		commentStar
				.setOnCommnetLayoutClickListener(new StarLayout.OnLayoutClickListener() {
					@Override
					public void onLookComment() {
						Intent intent = new Intent(GoodsDetailActivity.this,
								CommentList.class);
						intent.putExtra("goods_id", goods.getId() + "");
						intent.putExtra("goods_name", goods.getName());
						startActivity(intent);
					}

					@Override
					public void onAddComment() {
						if("".equals(userName)){
							String title = res.getString(R.string.not_login);
							String msg = res.getString(R.string.login_or_not);
							Intent loginIntent = new Intent(GoodsDetailActivity.this,
									LoginDialog.class);
							showDialog(title, msg, "确定","取消", loginIntent);
							return;
						}
						Intent intent = new Intent(GoodsDetailActivity.this,
								CommentActivity.class);
						intent.putExtra("userName", userName);
						intent.putExtra("goodsId", goods.getId() + "");
						startActivity(intent);
					}
				});

		// 启动线程，该线程主要用于实时加载商品的评论统计信息（即打分的详情）
		Thread myThread = new Thread(new DetailThread());
		myThread.start();

	}

	// 将订单数据插入到本地数据库（orderItem）
	private long insertInDB() {
		OrderDBHelper dbHelper = new OrderDBHelper(this);
		if (dbHelper.selectOne(goods.getId(), userName) > 0) {
			// 表示数据库中已有该数据
			return 0;
		}
		return dbHelper.saveOrderItem(goods.getId(), goods.getSellerId(),
				userName);
	}

	// 显示对话框
	public void showDialog(String title, String msg, String positive,
			String negative, final Intent intent) {
		LwtAlertDialog.Builder builder = new LwtAlertDialog.Builder(
				GoodsDetailActivity.this);
		builder.setTitle(title)
				.setMessage(msg)
				.setPositiveButton(positive,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								startActivity(intent);
							}
						}).setNegativeButton(negative, null);
		Dialog d = builder.create();
		d.show();
	}

	@Override
	protected void onResume() {
		super.onResume();
		PreferenceTools prefTools = new PreferenceTools(this);
		// 判断是否已经登录
		if (!prefTools.isLogin()) {
			return;
		}
		// 登录后修改登录按钮上的text
		userName = prefTools.getUserName();
		if (!userName.equals("")) {
			// OEM++ 修正跳转到购物车页面
			// 当用户登录后，修改登录按钮为查看购物车按钮
			if (Util.OEM) {
				login_bt.setText(null);
				// 去掉登录按钮文本右边的图标
				login_bt.setCompoundDrawablesWithIntrinsicBounds(null, null,
						null, null);
				// 设置监听器
				login_bt.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(getApplicationContext(),
								CartActivity.class);
						startActivity(intent);
					}
				});
				// 修改购物车图标
				setCartIcon();
			} else {
				login_bt.setText(userName);
				// 去掉登录按钮文本右边的图标
				login_bt.setCompoundDrawablesWithIntrinsicBounds(null, null,
						null, null);
			}
		}
	}

	// OEM++ 当购物车中商品数量改变时设置相应的图标
	private void setCartIcon() {
		OrderDBHelper dbHelper = new OrderDBHelper(this);
		int count = dbHelper.getItemCount(userName);
		if (count <= 10) {
			login_bt.setBackgroundResource(Util.cartIcon[count]);
		} else {
			login_bt.setBackgroundResource(Util.cartIcon[Util.cartIcon.length - 1]);
		}
	}

	// OEM--

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// 获得商品评论统计的json数据
			String jsonString = msg.getData().getString("comment_count");
			if ("".equals(jsonString))
				return;
			Gson gson = new Gson();
			// 将Json数据转化为实体
			CommentCount comC = gson.fromJson(jsonString, CommentCount.class);
			// 设置布局
			commentStar.setComment(comC.getStar1(), comC.getStar2(),
					comC.getStar3(), comC.getStar4(), comC.getStar5());

		}
	};

	class DetailThread implements Runnable {
		@Override
		public void run() {
			String commentCountJson = "";
			// 从服务器端下载商品评论及统计Json数据
			// 使用apache HTTP客户端实现
			String urlStr = Util.BASE_URL + "/servlet/CommentCountServlet";
			// 创建网络连接工具对象
			HttpHelper helper = new HttpHelper(urlStr);
			// 添加参数
			// 商品Id
			helper.addParam("goods_id", goods.getId() + "");
			// 获得服务器返回的数据
			commentCountJson = helper.getResponse();
			// 发送一个消息，以改变布局的显示
			Message msg = handler.obtainMessage();
			Bundle data = new Bundle();
			data.putString("comment_count", commentCountJson);
			msg.setData(data);
			handler.sendMessage(msg);
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && addToFavor) {
			setResult(RESULT_OK);
		}
		return super.onKeyDown(keyCode, event);
	}

	// OEM++手势滑动 李文涛@2013-1-15
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	/**
	 * 用户按下触摸屏、快速移动后松开
	 */
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		Log.i("MyGesture", "onFling");

		final int FLING_MIN_DISTANCE = 100, FLING_MIN_VELOCITY = 200;
		if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// Fling right
			LeftMenu.prepare(GoodsDetailActivity.this, R.id.goods_detail_layout);
			startActivity(new Intent(GoodsDetailActivity.this, LeftMenu.class));
			overridePendingTransition(0, 0);
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	public boolean onTouch(View v, MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	/**
	 * 解决ScrollView后不执行左右移动监听事件OnGestureListener
	 * 在Activity中添加ScrollView实现滚动activity的效果后，activity的滑动效果却无法生效了
	 * 原因是因为activity没有处理滑动效果，重写以下方法即可解决。
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		gestureDetector.onTouchEvent(ev);
		return super.dispatchTouchEvent(ev);
	}

	// OEM --

	// OEM++ 2013-02-27 监听菜单按钮事件，实现与手势相同的滑动效果
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		LeftMenu.prepare(GoodsDetailActivity.this, R.id.goods_detail_layout);
		startActivity(new Intent(GoodsDetailActivity.this, LeftMenu.class));
		overridePendingTransition(0, 0);
		return false;
	}
	// OEM--

}
